import {ref} from 'vue'
import {defineStore} from 'pinia'
import API from '@/api'

import type  { MicroApp, ObjectType, RegistrableApp } from 'qiankun'
import type {MicroConfig, NormalizeCallback} from '@/typings/micro'

function nomalizeMicroAppConfig(config: MicroConfig[], callback?: NormalizeCallback): RegistrableApp<ObjectType>[] {
  const microApps: RegistrableApp<ObjectType>[] = config.map(config => {
    const {name, entry, container, activeRule, isRouteStart} = config
    let data= {
      name,
      entry,
      container: container || `#${name}`,
      activeRule,
      // activeRule: (location: Location) => {
      //   if(location.hash) {
      //     return false
      //   } else {
      //     let regExp = new RegExp(`/micro/${name}`)
      //     return regExp.test(location.pathname)
      //   }
      // },
      // 默认 true
      isRouteStart: isRouteStart || true,
      sandbox: {
        stictStyleIsolation: true
      },
      props: {
        testName: 'mal',
        rawRule: activeRule
      }
    }

    let value = callback?.(data)

    return value || data
  })

  return microApps
}

// 获取当前的基础路径  如: getPathPrefix('/user/age/xxx', '/') => '/user'
export function getPathPrefix(path: string, prefix: string = '') {
  if (!path) return
  const pathArray = String(path).split('/').filter(item => item)
  const basePath = prefix + pathArray[0]
  console.log('basePath: ', basePath)
  return basePath
}

export const useMicroAppStore = defineStore('micro', () => {
  // 配置信息
  const MICRO_APP_CONFIG = ref<MicroConfig[]>([])
  // 微应用列表
  const microApplicationList = ref<Map<string, MicroApp>>(new Map)

  function setMicroAppConfig(config: MicroConfig[]) {
    MICRO_APP_CONFIG.value = config
  }

  // 设置微应用列表
  function SET_MICRO_APPLICATION_LIST(key: string, value: MicroApp){
    microApplicationList.value.set(key, value)
  }

  // 通过路径获取应用配置
  function GET_FIND_MICRO_CONFIG(path: string) {
    return MICRO_APP_CONFIG.value.find(configItem => {
      // return getPathPrefix(path, '/') === getPathPrefix(configItem.props.rawRule, '/')
      return configItem.activeRule?.(path) || path.startsWith(configItem.props.rawRule)
    })
  }

  function generateMicroAppConfig(callback: NormalizeCallback) {
    return new Promise<MicroConfig[]>((resolve, reject) => {
      API.getMicroAppConfig().then(res => {
        // 标准化配置数据
        const config = nomalizeMicroAppConfig(res.data as MicroConfig[], callback)
        // 设置值
        setMicroAppConfig(config)
        resolve(config)
      }).catch(err => {
        // 出错
        console.error(err)
      })
    })
  }


  return {
    MICRO_APP_CONFIG,
    microApplicationList,
    generateMicroAppConfig,
    SET_MICRO_APPLICATION_LIST,
    GET_FIND_MICRO_CONFIG
  }
})